﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AzureProvider.MiniSensor;
using AzureProvider.ssdsClient;
using BlogEngine.Core;
using System.Globalization;

namespace AzureProvider.SoupMethods.MiniSensor
{
    public class MessageMethods:BaseMethods
    {
        protected override string containerId
        {
            get { return "MiniSensor"; }
        }

        protected override string kind
        {
            get { return "Message"; }
        }

        protected override AzureProvider.ssdsClient.Entity CreateEntity(object Object)
        {
            Message message = (Message)Object;

            var entity = new Entity()
            {
                Id = message.Id.ToString(),
                Kind = kind
            };

            entity.Properties = new Dictionary<string, object>();
            entity.Properties.Add("Author", message.Author);
            entity.Properties.Add("Content", message.Content);
            entity.Properties.Add("DateCreated", message.DateCreated.AddHours(BlogSettings.Instance.Timezone).ToString("yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture));
            entity.Properties.Add("ChannelId", message.ChannelId.ToString());
            return entity;
        }

        public override object CreateObject(AzureProvider.ssdsClient.Entity Entity)
        {
            Message message = new Message
            {
                Id = new Guid(Entity.Id),
                Author = (string)Entity.Properties["Author"],
                Content = (string)Entity.Properties["Content"],
                DateCreated = DateTime.Parse((string)Entity.Properties["DateCreated"]),
                ChannelId= new Guid((string)Entity.Properties["ChannelId"])
            };
            return message;
        }
        public IEnumerable<Message> GetMessages(string ChannelId, out string errMessage)
        {
            string qry=null;
            if (ChannelId != null)
                qry = string.Format(" from e in entities where e.Kind == \"{0}\" && e[\"ChannelId\"] == \"{1}\" orderby e[\"DateCreated\"] descending select e ", kind, ChannelId);
            
            return base.GetObjects(qry, out errMessage).Cast<Message>();
        }
    }
}
